/**
 * @(#)ClientProxy.java, Sep 19, 2012. 
 * 
 * Copyright 2012 Yodao, Inc. All rights reserved.
 * YODAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.buaaer.mina;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;

/**
 * this class will return a client proxy of some interface
 * 
 * @author wangheng
 *
 */
public class ClientProxy {
    
    /**
     * server address
     */
    private InetSocketAddress addr;
    
    /**
     * the real client
     */
    Client client;
    
    /**
     * constructor
     * 
     * @param host
     * @param port
     */
    public ClientProxy(String host, int port) {
        this.addr = new InetSocketAddress(host, port);
    }
    
    /**
     * get the proxy
     * @param invocationInterfaces
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T getProxy(Class<T> invocationInterfaces) {
        
        client = new  Client(addr);
        client.init();
        ClientInvocationHandler handler = new ClientInvocationHandler(client);
        
        return (T) Proxy.newProxyInstance(
                invocationInterfaces.getClassLoader(), 
                new Class<?>[]{invocationInterfaces},
                handler);
        
    }
    
}

class ClientInvocationHandler implements InvocationHandler {
    
    Client client;
    
    public ClientInvocationHandler(Client client) {
        this.client = client;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        
        CallBody callBody = new CallBody(method.getName(),
                method.getParameterTypes(), args);
        
        FutureResult result =  client.submit(callBody);
        DataPackage obj =  result.get();
        System.out.println("obj:" + obj);
        return obj.getObject();
    }

}



